# !/usr/bin/env python
# -*- coding:utf-8 -*-
'''项目管理器

历史:
    2018-11-30 姚彧 创建
'''

__all__ = ['ProjectManager', 'Project']

import os
from tool.Singleton import MetaSingleton
from tool.AttributesTable import AttributesTable
from events.EventCenter import (EventContext, EventDispatcher)
from events.EventNames import EventNames

class Project(object):
    def __init__(self, project_dir):
        assert os.path.isdir(project_dir), project_dir
        self.project_dir = project_dir
        self.project_name = os.path.basename(project_dir)
        self.attrib_table = AttributesTable(os.path.join(project_dir, 'yDelaunator.db'))
        self.prop_table = self.attrib_table

    def get_value(self, key, default = None):
        return self.prop_table.get_value(key, default)

    def set_value(self, key, value):
        self.prop_table.set_value(key, value)

    def set_file(self, key, value):
        value = os.path.abspath(value)
        project_dir = os.path.abspath(self.project_dir)
        try:
            new_value = os.path.relpath(value, project_dir)
            value = new_value
        except:
            pass
        self.set_value(key, value)

    def get_file(self, key):
        value = self.get_value(key)
        if not value:
            return
        if ':' in value:
            return value
        value = os.path.abspath(os.path.join(self.project_dir, value))
        return value

class ProjectManager(object, metaclass = MetaSingleton):
    def __init__(self):
        self.project = None

    def emit(self, *args, **kwargs):
        return EventDispatcher().emit(*args, **kwargs)

    def get_dir(self, subdir = None):
        if self.project and isinstance(subdir, str):
            return os.path.join(self.project.project_dir, subdir)

    def on_project_created(self, context: EventContext):
        assert context.path == EventNames.Project_Created
        self.project = context['project']

    def on_project_opened(self, context: EventContext):
        assert context.path == EventNames.Project_Opened
        self.project = context['project']

    def on_project_close(self, context: EventContext):
        assert context.path == EventNames.Project_Close
        self.project = None

    @classmethod
    def register_events(cls):
        self = cls()
        EventDispatcher().register(EventNames.Project_Created, self.on_project_created)
        EventDispatcher().register(EventNames.Project_Opened, self.on_project_opened)
        EventDispatcher().register(EventNames.Project_Close, self.on_project_close)

